<template>
  <div class="page">
    <div class="top" style="padding-right:0;">
      <div style="float:left;"><span>组态名称：{{viewName}}</span></div>
      <!-- <el-button type="primary" size="small" id="goback" @click="goList">返回</el-button> -->
      <el-button type="primary" size="small" id="goback" @click="replaceSensor">确认替换</el-button>
      <!-- <el-button type="success" size="small"   style="position:fixed;bottom:1.5rem;right:1rem;z-index:999;" @click="replaceSensor">确认替换</el-button> -->
      <!-- <el-button type="primary" size="small" id="goback" style="margin-right:0.2rem;" @click="refreshView">刷新</el-button> -->
    </div>
    <div class="main">
      <div class="viewBox_2" v-if="drawList.length>1">
        <div class="oneView_2 over" :class="nowDraw==item.label?'active':''" v-for="(item,i) in drawList" :key="i"
          @click="changeStage(item,$event)"><span>{{item.label}}</span></div>
      </div>
      <div v-if="pointsList.length">
        <div class="container_table" v-for="(item,n) in pointsList" :key="item.equip_id+'k'">
          <div class="equipBar">
            <div class="oldEquip">原设备名称：<span>{{item.equip_name}}</span></div>
            <div class="newEquip">新设备名称：
              <el-select v-model="item.newEquip" placeholder="选择新设备" class="inpu"
                @change="changeEquip(item.newEquip,n)">
                <el-option v-for="item in equips" :key="item.value" :value="item.value" :label="item.label">
                </el-option>
              </el-select><span
                style="font-size: 0.3rem;font-weight: normal;margin-left:0.2rem;">新变量为空,替换后将清除原变量绑定关系</span>
            </div>
          </div>
          <el-table :data="item.sensors" size="small" border v-loading.fullscreen="loading"
            element-loading-text="正在自动匹配,请稍等..." element-loading-spinner="el-icon-loading"
            style="width: 99.4%;margin-top:0.1rem;" :header-cell-style="{
				'background-color':tableHead,
				'color': 'white',
		        'fontSize':'0.3rem'
			}" :cell-style="{'fontSize':'0.3rem','padding':'0.1rem 10px'}">
            <!-- <el-table-column type="selection" min-width="30">
				</el-table-column> -->
            <!-- <el-table-column label="ID" prop="id" align="center" min-width="50">
				</el-table-column> -->
            <el-table-column label="原子设备名称" align="center" min-width="120">
              <template slot-scope="scope">
                <span>{{scope.row.slave_name?scope.row.slave_name:'——'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="sensor_name" label="原变量名称" align="center" min-width="200">
            </el-table-column>
            <el-table-column prop="new_slave_id" label="新子设备名称(未匹配将默认第一子设备)" align="center" min-width="120">
              <template slot-scope="scope">
                <el-select v-if="scope.row.slaves[0]" v-model="scope.row.new_slave_id" placeholder="选择新子设备"
                  class="inpu_2" @change="changeSlave(scope.$index,n,scope.row.new_slave_id)">
                  <el-option v-for="item in scope.row.slaves" :key="item.value" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
                <span v-else>——</span>
              </template>
            </el-table-column>
            <el-table-column label="新变量名称" align="center" min-width="200">
              <template slot-scope="scope">
                <el-select v-model="scope.row.new_sensor_code" placeholder="选择新变量" class="inpu_2"
                  @focus="getNewSensor($event,n,scope.$index,scope.row.newSensors.length)">
                  <el-option v-for="item in scope.row.newSensors" :key="item.value" :value="item.value"
                    :label="item.label">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

          </el-table>

        </div>
      </div>
      <div v-else style="color:#ccc;font-size:0.35rem;">
        该图纸尚未绑定数据点或数据点已被移除！
      </div>
    </div>

  </div>
</template>

<script>
  export default {
    name: 'changeVar',
    data() {
      return {
        viewName: localStorage.getItem("editViewName"),
        optionId: localStorage.getItem("optionId"),
        tableHead: localStorage.getItem("bgcolor"),
        pointsList: [],
        changePoints: {},
        loading: false,
        equips: [],
        drawName: '',
        viewId: 0,
        stageId: 0,
        nowDraw: '',
        drawList: []
        //url:'static/jyzt/index_edit.html?stageId=df45524566322&selectOneWhere=122534'
      }
    },
    created() {
      this.optionId = Number(localStorage.getItem("optionId"));
      this.viewId = localStorage.getItem("editViewId");
      this.getDraws();
      this.getEquips();
    },
    mounted() {

    },
    methods: {
      goList() {
        this.$router.push({
          name: 'viewList',
          path: 'viewList',
          component: 'viewList'
        });
      },

      getEquips() {
        var that = this;
        this.$http({
            method: 'post',
            url: 'api/equip/all',
            data: {
              'product_id': this.optionId

            }
          })
          .then(res => {
            if (res && res.data.result == "success") {
              for (var i = 0; i < res.data.data.length; i++) {
                var equip = {
                  value: res.data.data[i].id,
                  label: res.data.data[i].equip_name
                }
                this.equips.push(equip)
              }
              //this.option = this.options[0].value;
            }
          }).catch(error => {
            console.log(error)
            this.equips = [];
          });
      },

      getDraws() {
        var that = this;
        this.$http({
          method: 'post',
          url: 'api/draw/all',
          data: {
            'view_id': this.viewId
            //'keyword': keyword
          }
        }).then(res => {
          if (res && res.data.result == "success") {
            for (var i = 0, len = res.data.data.length; i < len; i++) {
              var draw = {
                value: res.data.data[i].id,
                label: res.data.data[i].draw_name
              }
              this.drawList.push(draw);
            }
            this.stageId = this.drawList[0].value;
            this.nowDraw = this.drawList[0].label;
            this.getPoints(that.stageId);
          }
        }).catch(error => {
          console.log(error);
          this.drawList = [];

        });
      },

      async getSlave(id) {
        var that = this;
        var slaveList = [];
        var slaves = await this.$http({
          method: 'post',
          url: 'api/slave/all',
          data: {
            'equip_id': id

          }
        }).then(res => {
          if (res && res.data.result == "success") {
            for (var i = 0, len = res.data.data.length; i < len; i++) {
              var slave = {
                value: res.data.data[i].id,
                label: res.data.data[i].slave_name
              }
              slaveList.push(slave);
            }
            return slaveList
          }
        }).catch(error => {
          console.log(error)
          // slaveList=[];
        });

        return slaves;
      },

      async getSensors(slaveId, equipId) {
        var that = this;
        var sensors = await this.$http({
          method: 'post',
          url: 'api/sensor/all',
          data: slaveId && slaveId != 0 ? {
            'slave_id': slaveId

          } : {
            'equip_id': equipId

          }
        }).then(res => {
          if (res && res.data.result == "success") {
            var sensorList = [];
            for (var i = 0, len = res.data.data.length; i < len; i++) {
              var sensor = {
                value: res.data.data[i].sensor_code,
                label: res.data.data[i].sensor_name
                //sensor_code:res.data.data[i].sensor_code
              }
              sensorList.push(sensor);
            }
            return sensorList
          }
        }).catch(error => {
          console.log(error)
          // slaveList=[];
        });

        return sensors;
      },

      async getAutoMatch(id, oldEquip, newEquip) {
        // var sensors=[];
        var autoSensors = await this.$http({
          method: 'post',
          url: 'api/draw/automatch',
          data: {
            'id': id,
            'old_equip_id': oldEquip,
            'new_equip_id': newEquip

          }
        }).then(res => {
          if (res && res.data.result == "success") {
            return res.data.data;
          } else {
            return [];
          }
        }).catch(error => {
          console.log(error)
          //sensors=[];
        });

        return autoSensors;
      },


      changeStage(item, event) {
        var that = this;
        if (event.target.innerText == item.label) {
          this.nowDraw = item.label;
        }
        this.stageId = item.value;
        this.getPoints(that.stageId);
      },

      //判断数组对象的某个属性值是否是value
      checkSameValue(arr, property,value) {
        let values = arr.map(function(obj) {
          return obj[property];
        });
        let newArr = value.split('@');
        let newValue = newArr[0]+'@'+newArr[1];
        // 使用every()方法判断是否每个元素都相等
        var isSame = values.includes(newValue);
        return isSame;
      },

      matchSensor(index, slaves, mySensors, sensorslist) {
      	for (let i = 0, len = this.pointsList[index].sensors.length; i < len; i++) {
      		this.pointsList[index].sensors[i].slaves = slaves;
      		//this.pointsList[index].sensors[i].newSensors=mySensors;
      		//先默认是第一个从机，没匹配上的也就默认第一个从机
      		this.pointsList[index].sensors[i].new_slave_id = slaves[0].value;
      		//对比sensor_code,把设备ID排除掉
      		let oldArr = this.pointsList[index].sensors[i].sensor_code?this.pointsList[index].sensors[i].sensor_code.split('@'):[];
      		let oldValue = oldArr.length?oldArr[0]+'@'+oldArr[1]:'';
      		if(sensorslist.length){
      			for (let n = 0, len2 = sensorslist.length; n < len2; n++) {
      				//对比sensor_code,把设备ID排除掉
      				let newArr = sensorslist[n].new_sensor_code?sensorslist[n].new_sensor_code.split('@'):[];
      				let newValue = newArr.length?newArr[0]+'@'+newArr[1]:'';
      				//新，旧设备sensor_code截取后对比
      				if (oldValue == newValue) {
      					this.pointsList[index].sensors[i].new_slave_id = sensorslist[n].new_slave_id;
      					this.pointsList[index].sensors[i].new_sensor_id = sensorslist[n].new_sensor_id;
      					this.pointsList[index].sensors[i].new_sensor_name = sensorslist[n].new_sensor_name;
      					this.pointsList[index].sensors[i].new_sensor_code = sensorslist[n].new_sensor_code;
      					if (this.pointsList[index].sensors[i].newSensors.length == 0) {
      						//console.log(this.checkSameValue(mySensors,'value',sensorslist[n].new_sensor_code))
      						if (this.checkSameValue(mySensors, 'value', sensorslist[n].new_sensor_code)) {
      							this.pointsList[index].sensors[i].newSensors = mySensors;
      						} else {
      							this.pointsList[index].sensors[i].newSensors = [{
      								value: sensorslist[n].new_sensor_code,
      								label: sensorslist[n].new_sensor_name
      							}]
      						}
      					}
      				}

      			}
      		}
      	}
      	this.$forceUpdate();
      	this.loading = false;
      },

      async changeEquip(equip, index) {
      	var that = this;
      	var sensorslist = [];
      	var slaves = [];
      	var itemSensors = [];
      	this.loading = true;
      	for (let i = 0, len = this.pointsList[index].sensors.length; i < len; i++) {
      		this.pointsList[index].sensors[i].slaves = [];
      		this.pointsList[index].sensors[i].newSensors = [];
      		this.pointsList[index].sensors[i].new_slave_id = "";
      		this.pointsList[index].sensors[i].new_sensor_id = "";
      		this.pointsList[index].sensors[i].new_sensor_code = "";
      		this.pointsList[index].sensors[i].new_sensor_name = "";
      	}
      	await this.getAutoMatch(this.stageId, this.pointsList[index].equip_id, equip).then(res => {
      		sensorslist = res;
      	}).catch(err => {
      		console.log(err)
      	});
      	await this.getSlave(equip).then(resSlave => {
      		slaves = resSlave;
      		if (sensorslist.length && sensorslist[0].new_slave_id) {
      			that.getSensors(sensorslist[0].new_slave_id, 0).then(resSensor => {
      				itemSensors = resSensor;
      				that.matchSensor(index, slaves, itemSensors, sensorslist);
      			});
      		} else {
      			//that.getSensors(0, equip).then(resSensor => {
      				//itemSensors = resSensor;
      				that.matchSensor(index, slaves, [], sensorslist);

      			//});
      		}
      	}).catch(err => {
      		console.log(err)
      	});
      	this.loading =false;
      },

      async changeSlave(index, equipIndex, slaveId) {
        var that = this;
        var itemSensors=[];
        this.pointsList[equipIndex].sensors[index].newSensors = [];
        this.pointsList[equipIndex].sensors[index].new_sensor_id = "";
        this.pointsList[equipIndex].sensors[index].new_sensor_name = "";
        this.pointsList[equipIndex].sensors[index].new_sensor_code = "";
        this.$forceUpdate();
        if (slaveId && slaveId !== '0') {
          await this.getSensors(slaveId, '').then(res => {
            itemSensors=res;
            that.pointsList[equipIndex].sensors[index].newSensors = itemSensors;
            that.$forceUpdate();
          });
        } else {
          await this.getSensors(0, this.pointsList[equipIndex].equip_id).then(res => {
            itemSensors=res;
            that.pointsList[equipIndex].sensors[index].newSensors = itemSensors;
            that.$forceUpdate();
          });
        }

      },

      getNewSensor(e, deviceIndex, index, len) {
        //console.log(deviceIndex,index,len);
        var that = this;
        let deviceId = this.pointsList[deviceIndex].equip_id;
        let slaveId = this.pointsList[deviceIndex].sensors[index].new_slave_id;
        let itemSensors = [];
        if (len <= 1) {
          this.getSensors(slaveId, deviceId).then(res => {
            itemSensors = res;
            this.pointsList[deviceIndex].sensors[index].newSensors = itemSensors;
            this.$forceUpdate();
          });
        }
      },

      preChange() {
        var that = this;
        this.changePoints = {};
        for (let i = 0, len = this.pointsList.length; i < len; i++) {
          for (let n = 0, len2 = this.pointsList[i].sensors.length; n < len2; n++) {
            this.$set(that.changePoints, that.pointsList[i].sensors[n].sensor_code, that.pointsList[i].sensors[n]
              .new_sensor_code || "");
          }
        }
      },


      async sureReplaceSensor() {
        var that = this;
        await this.preChange();
        this.$http({
          method: 'post',
          url: 'api/draw/replacePoints',
          data: {
            'id': this.stageId,
            'points': this.changePoints
          }
        }).then(res => {
          if (res && res.data.result == "success") {
            this.$message({
              message: '恭喜，变量替换成功!',
              type: 'success',
              center: true
            })
            this.getPoints(this.stageId);
          }
        }).catch(error => {
          console.log(error);
        });
      },

      replaceSensor() {
        this.$confirm('替换成功后将覆盖组态原有变量配置,请确保替换正确,否则无法正常显示和操控! 是否确认替换?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.sureReplaceSensor();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消变量替换'
          });
        });
      },

      getPoints(id) {
        this.$http({
          method: 'post',
          url: 'api/draw/points',
          data: {
            'id': id
          }
        }).then(res => {
          if (res && res.data.result == "success") {
            this.pointsList = res.data.data;
            for (let i = 0, len = this.pointsList.length; i < len; i++) {
              this.$set(this.pointsList[i], 'newEquip', '');
              for (let n = 0, len2 = this.pointsList[i].sensors.length; n < len2; n++) {
                this.$set(this.pointsList[i].sensors[n], 'slaves', []);
                this.$set(this.pointsList[i].sensors[n], 'newSensors', []);
              }
            }
            this.$forceUpdate();
          }
        }).catch(error => {
          console.log(error);
          this.pointsList = [];

        });
      }
    }
  }
</script>

<style scoped>
  @media all and (max-width:2560px) {
    .main {
      height: 21.8rem !important;
    }

  }

  @media all and (max-width:1920px) {
    .main {
      height: 14.8rem !important;
    }

  }

  .viewBox_2 {
    margin-top: 0.2rem;
    width: 99.4%;
    min-height: 34px;
    max-height: 102px;
    line-height: 34px;
    overflow: auto;
    color: white;
    font-size: 0.3rem;
    text-align: left;
    border-bottom: 1px solid #ccc;
  }

  .oneView_2 {
    max-width: 250px;
    min-width: 80px;
    display: inline-block;
    height: 30px;
    /* margin-top:5px; */
    line-height: 30px;
    padding: 0 0.2rem;
    text-align: center;
    color: #222;
    /* background-color:rgba(0,0,0,0.8); */
    /*deepskyblue透明度0.5*/
    background-color: #ccc;
    border-radius: 4px;
  }

  .active {
    background-color: rgba(0, 191, 255, 1);
    color: #fff;
    /* border:1px solid #E6A23C; */
  }

  /* .active_2{
		color:#409Eff;
		background-color:rgba(0,0,0,0.6);
		border:1px solid #409Eff;
	} */

  .oneView_2 {
    margin-right: 0.2rem;
  }

  .container_table {
    margin-top: 0.2rem;
  }

  .inpu,
  .inpu_2 {
    width: 5rem;
    vertical-align: middle;
  }

  .inpu_2 {
    margin-top: 0 !important;
    border: none !important;
    height: 0.6rem !important;
    line-height: 0.6rem !important;
  }

  .inpu /deep/ .el-input__inner {
    height: 0.8rem;
    line-height: 0.8rem;
  }

  .inpu_2 /deep/ .el-input__inner {
    height: 0.6rem !important;
    line-height: 0.6rem !important;
  }

  .inpu_2 /deep/ .el-input__icon {
    line-height: 30px !important;
  }

  .equipBar {
    width: auto;
    height: 0.8rem;
    text-align: left;
    line-height: 0.8rem;
    font-size: 0.35rem;
    margin-top: -0.1rem;
    margin-bottom: 0.1rem;
    /* border:1px solid red; */
  }

  .equipBar span {
    font-weight: 700;
  }

  .oldEquip,
  .newEquip {
    width: 50%;
    float: left;
  }

  .main {
    height: 14.8rem;
    width: 100%;
    overflow: auto;
    /* border:1px solid red; */
  }
</style>
